package com.lzjn.code.web.controller;

import com.lzjn.code.common.constant.Constants;
import com.lzjn.code.common.model.JsonModel;
import com.lzjn.code.common.model.PageModel;
import com.lzjn.code.web.entity.DataSource;
import com.lzjn.code.web.service.DataSourceService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/dataSource")
public class DataSourceController {

	private static final Logger log = LoggerFactory.getLogger(DataSourceController.class);
	
	@Autowired
	private DataSourceService dataSourceService;
	
	@GetMapping("/init")
	public String init(){
		
		return "views/dataSource/dataSourceList";
	}
	
	@PostMapping("/getData")
	@ResponseBody
	public PageModel getData(DataSource dataSource, PageModel page){
		
		try {
			
			page = dataSourceService.getByPage(dataSource, page);
		} catch (Exception e) {
			
			log.error(e.getMessage(), e);
		}
		
		return page;
	}
	
	@GetMapping("/dataSource")
	public String dataSource(String id,HttpServletRequest request) {
		
		try {
			
			if(StringUtils.isNotEmpty(id)) {
				
				request.setAttribute("dataSource", dataSourceService.getById(id));
			}
		} catch (Exception e) {
			
			log.error(e.getMessage(), e);
		}
		
		return "views/dataSource/dataSourceEdit";
	}
	
	@PostMapping("/save")
	@ResponseBody
	public JsonModel save(DataSource dataSource) {
		
		JsonModel json = new JsonModel();
		
		try {
			
			if(StringUtils.isNotEmpty(dataSource.getId())) {
				
				json.setMessage(dataSourceService.update(dataSource));
			}
			else {
				
				json.setMessage(dataSourceService.add(dataSource));
			}
			
		} catch (Exception e) {
			
			json.setSuccess(false);
			json.setMessage(Constants.MESSAGE_SAVE_FAIL);
			log.error(e.getMessage(), e);
		}
		
		return json;
	}
	
	@PostMapping("/delete")
	@ResponseBody
	public JsonModel delete(String ids) {
		
		JsonModel json = new JsonModel();
		
		try {
			
			if(StringUtils.isNotEmpty(ids)) {
				
				json.setMessage(dataSourceService.delete(ids));
			}
		} catch (Exception e) {
			
			json.setSuccess(false);
			json.setMessage(Constants.MESSAGE_DELETE_FAIL);
			log.error(e.getMessage(), e);
		}
		
		return json;
	} 
	
}
